﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.Adapters;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using zevenseas.SharePoint.Solutions.FeatureBlocker.ApplicationPages;


namespace zevenseas.SharePoint.Solutions.FeatureBlocker
{
    public class FeatureBlockerAdapter : ControlAdapter
    {
        private List<string> featureCollection;
        private TypeOfAction typeOfAction;
        private string actionUrl;
        private bool excludeFarmAdmin;

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            string scope = Page.Request.QueryString["Scope"];
            if (string.IsNullOrEmpty(scope))
            {
                scope = "Web";
            }
            //Getting the configuration from the Persistence Store
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                SPWebApplication webApplication = SPWebApplication.Lookup(SPContext.Current.Site.WebApplication.GetResponseUri(SPUrlZone.Default));
                FeatureCollection settings = webApplication.GetChild<FeatureCollection>("FeatureCollection" + scope);
                if (settings != null)
                {
                    featureCollection = settings.Features;
                }

                FeatureBlockerConfig config = webApplication.GetChild<FeatureBlockerConfig>("FeatureBlockerConfig");
                if (config != null)
                {
                    typeOfAction = config.Action;
                    actionUrl = config.redirectUrl;
                    excludeFarmAdmin = config.ExcludeFarmAdmin;
                }

            });

            //Overriding the current output
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
            base.Render(htw);

            string fullFeatureTable = string.Empty;
            bool skipBlock = false;


            if (excludeFarmAdmin)
            {
                if (SPFarm.Local.CurrentUserIsAdministrator())
                {
                    skipBlock = true;
                }
            }


            if (!skipBlock)
            {
                if (featureCollection.Count > 0)
                {
                    fullFeatureTable = htw.InnerWriter.ToString();

                    foreach (string feature in featureCollection)
                    {
                        string output = feature;
                        if (feature.StartsWith("{"))
                        {
                            output = output.Replace("{", "");
                        }
                        if (feature.EndsWith("}"))
                        {
                            output = output.Replace("}", "");
                        }

                        //Check if the Feature is available on the page
                        int divPosition = fullFeatureTable.IndexOf("'" + output + "'");

                        //Only process the current HTML if the feature is found
                        if (divPosition != -1)
                        {
                            int onClickPosition = fullFeatureTable.IndexOf("onclick=", divPosition);

                            switch (typeOfAction)
                            {
                                case TypeOfAction.Redirect:
                                    int idPosition = fullFeatureTable.IndexOf("id=", divPosition);
                                    string onClickString = fullFeatureTable.Substring(onClickPosition, (idPosition - onClickPosition));
                                    string newOnClickString = "onClick=\"parent.location='" + actionUrl + feature+ "'\"";
                                    fullFeatureTable = fullFeatureTable.Replace(onClickString, newOnClickString);

                                    break;
                                case TypeOfAction.Block:
                                    fullFeatureTable = fullFeatureTable.Insert(onClickPosition - 1, " Disabled='true' ");
                                    break;
                                case TypeOfAction.Hide:
                                    fullFeatureTable = fullFeatureTable.Insert(fullFeatureTable.Length - 1, "<script>document.getElementById('" + output + "').parentNode.parentNode.style.display = 'none';</script>");
                                    break;
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(fullFeatureTable))
            {
                writer.Write(fullFeatureTable);
            }
            else
            {
                writer.Write(sb.ToString());
            }

        }
    }
}

